﻿#include "MainWindow.h"
#include "QWindow.h"
#include <iostream>
#include <QDebug>
#include <QPushButton>
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QStackedWidget>
#include <QStatusBar>
#include <QVBoxLayout>
#include <QApplication>
#include <QClipboard>
#include <QImage>
#include <QThread>
#include <QTimer>

#include "ElaContentDialog.h"
#include "ElaDockWidget.h"
#include "ElaEventBus.h"
#include "ElaLog.h"
#include "ElaMenu.h"
#include "ElaMenuBar.h"
#include "ElaProgressBar.h"
#include "ElaStatusBar.h"
#include "ElaText.h"
#include "ElaTheme.h"
#include "ElaToolBar.h"
#include "ElaToolButton.h"
#include "ElaMessageBar.h"
#include "CenterWidget.h"
#include "GenerateReportBase.h"
#include "CreateNewReport.h"
#include "T_TemplateDefinedWidget.h"
#include "insertScreenshotIntoReport.h"
#include "GemerateFinalReport.h"
#include "MiniFloatingWindow.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseModule/IBaseSignal.h"
#include "FinalReportData.h"
#include "globalenums.h"

namespace GenerateReport
{
    MainWindow::MainWindow(QWidget* parent)
        : ElaWindow(parent)
    {
        initWindow();

        //额外布局
        initEdgeLayout();
        //中心窗口
        initContentWidget(); 
        InitTimer();
        initProjectData();
       
        connect(IBaseSignalInstance, &BaseModule::IBaseSignal::signal_readyCloseApp, this, [=](bool& isClose) {
            //isClose = false;//false表示不允许关闭
            //IBaseSignalInstance->signal_sendErrorMessageToUI(QStringLiteral("程序正在运行中，暂时不能关闭，请稍候。"));
            saveProjectData();
            });

        //yr-窗口最小化和恢复的信号连接浮窗的显示与隐藏

        //移动到中心
        moveToCenter();
        GlobalHelperInstance->sendMsgToParentProcess(QString("{--}winId{||}%1{--}\n").arg(winId()));
    }

    MainWindow::~MainWindow()
    {
        std::string targetProcessName = "soffice.bin";
        qint64 processId = GlobalHelperInstance->getProcessIdByName(targetProcessName);
        GlobalHelperInstance->closeProcessByProcessId(processId);
        
        if (m_libreOffice)
        {
            m_libreOffice->close();
            delete m_libreOffice;
            m_libreOffice = Q_NULLPTR;
        }
        if (m_centerWidget)
        {
            delete m_centerWidget;
            m_centerWidget = nullptr;
        }
        if (m_pThread)
        {
            m_pThread->quit();
            m_pThread->terminate();
            //m_pThread->wait();
            delete m_pThread;
            m_pThread = Q_NULLPTR;
        }
        if (m_toolButtonCreateNewReport)
        {
            delete m_toolButtonCreateNewReport;
            m_toolButtonCreateNewReport = nullptr;
        } 
        if (m_toolButtonReportRecordForm)
        {
            delete m_toolButtonReportRecordForm;
            m_toolButtonReportRecordForm = nullptr;
        }
        if (m_miniFloatingWindow)
        {
            delete m_miniFloatingWindow;
            m_miniFloatingWindow = nullptr;
        }
        //if (m_pTimer)
        //{
        //    delete m_pTimer;
        //    m_pTimer = Q_NULLPTR;
        //}
    }

    void MainWindow::initWindow()
    {
        setIsNavigationBarEnable(false);
        setWindowButtonFlags(ElaAppBarType::StayTopButtonHint | ElaAppBarType::MinimizeButtonHint | ElaAppBarType::MaximizeButtonHint | ElaAppBarType::CloseButtonHint);
        setAppBarHeight(30);
        setWindowIcon(QIcon(":/QUI/image/GenerateReport_GenerateResultReport2x.png"));
        resize(1678, 921);
        setWindowTitle(QStringLiteral("报告生成"));
        GenerateReportBaseInstance->initUno();
        m_miniFloatingWindow = new MiniFloatingWindow();
    }

    void MainWindow::initEdgeLayout()
    {
        initToolBar();
        statusBarPromptInformation(QStringLiteral("初始化成功！"));
    }

    void MainWindow::InitTimer()
    {
        /// @brief 初始化线程定时器
        m_pThread = new QThread(this);
        m_pTimer = new QTimer();
        m_pTimer->moveToThread(m_pThread);
        m_pTimer->setInterval(100); //0.1秒读取一次
        connect(m_pThread, SIGNAL(started()), m_pTimer, SLOT(start()));
        connect(m_pThread, &QThread::destroyed, m_pTimer, &QTimer::deleteLater);
        connect(m_pTimer, &QTimer::timeout, this, &MainWindow::slots_Timer, Qt::DirectConnection);
        m_pThread->start();
        GlobalHelperInstance->sendMsgToParentProcess(QString("{--}result{||}%1{--}\n").arg("process started!"));
    }

    void MainWindow::initProjectData()
    {
        GlobalHelperInstance->initProjectTempDir();
        FinalReportDataInstance->readConfig();
    }

    void MainWindow::libreOfficeProcess(GenerateReport::ReportRelatedSubWidgetType widgetType, QPair<qint64, qint64> indexPair, QString reportName)
    {
        m_centerWidget->addReportRelatedSubWidget(widgetType, indexPair, reportName);
    }

    void MainWindow::slot_toolBtnClick_CreateNewReport()
    {
		auto _currentReportNum = GenerateReportBaseInstance->getCurrentReportNumber();
		if (_currentReportNum == 1)
		{
			//statusBarPromptInformation(QString("当前正在编辑一份报告，请先关闭或保存当前报告！"));
            auto _msg = QStringLiteral("当前正在编辑一份报告，请先关闭或保存当前报告！");
            ElaMessageBar::warning(ElaMessageBarType::PositionPolicy::Top, QStringLiteral("警告"), _msg, 3000, this);
			return;
		}


        GenerateReport::CreateNewReport *_tes= new GenerateReport::CreateNewReport;
        _tes->actionSlot_CreateNewReport();
    }

    void MainWindow::slot_toolBtnClick_TemplateDefined()
    {
        m_templateDefinedWidget = new T_TemplateDefinedWidget();
        m_templateDefinedWidget->setFixedSize(400, 400);
        m_templateDefinedWidget->moveToCenter();
        m_templateDefinedWidget->show();
    }
    void MainWindow::slot_toolBtnClick_TemplateImport()
    {
        ElaMessageBar::warning(ElaMessageBarType::PositionPolicy::Top, QStringLiteral("警告"), QStringLiteral("功能开发中！"), 3000, this);
    }
    void MainWindow::slot_toolBtnClick_TemplateExport()
    {
        ElaMessageBar::warning(ElaMessageBarType::PositionPolicy::Top, QStringLiteral("警告"), QStringLiteral("功能开发中！"), 3000, this);
    }

    void MainWindow::slot_toolBtnClick_GemerateFinalReport()
    {
        ElaToolButton* _btn = dynamic_cast<ElaToolButton*>(sender());
        if (_btn)
        {
            auto _currentReportNum = GenerateReportBaseInstance->getCurrentReportNumber();
            if (_currentReportNum == 0)
            {
                //statusBarPromptInformation(QString("当前没有正在编辑的报告，请先新建一份报告！"));
                auto _msg = QStringLiteral("当前没有正在编辑的报告，请先新建一份报告！");
                ElaMessageBar::warning(ElaMessageBarType::PositionPolicy::Top, QStringLiteral("警告"), _msg, 3000, this);
                return;
            }
            
            GenerateReport::GemerateFinalReport gfp;
            gfp.actionSlot_GemerateFinalReport();
        }
    } 
    void MainWindow::slot_toolBtnClick_ReportRecordForm()
    {
        QPair<qint64, qint64> _tempPair{ 0,0 };
        m_centerWidget->addReportRelatedSubWidget(GenerateReport::ReportRelatedSubWidgetType::ReportRecordFormSubWidget, _tempPair, QString(""));
    }

    void MainWindow::action_screenshotToReport()
    {
		//判断报告是否创建
		auto _currentReportNum = GenerateReportBaseInstance->getCurrentReportNumber();
		if (_currentReportNum == 1)
		{
			GenerateReport::insertScreenshotIntoReport insertImage;
			insertImage.actionSlot_insertScreenshotIntoReport();
		}
		else
		{
			GenerateReportBaseInstance->setCreateAndScreenshotToReport(true);
			slot_toolBtnClick_CreateNewReport();
		}
    }

    void MainWindow::closeReportWidget()
    {
        m_centerWidget->closeCurrentReportWidget();
    }

    void MainWindow::initToolBar()
    {
        //工具栏
        ElaToolBar* toolBar = new ElaToolBar(QStringLiteral("工具栏"), this);
        toolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
        toolBar->setAllowedAreas(Qt::NoToolBarArea);
        toolBar->setToolBarSpacing(5);
        toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
        toolBar->setIconSize(QSize(25, 25));
        toolBar->setFloatable(false);
        toolBar->setMovable(false);
        toolBar->setContentsMargins(QMargins(5, 5, 5, 5));

        m_toolButtonCreateNewReport = new ElaToolButton(this);
        m_toolButtonCreateNewReport->setIcon(QIcon(":/QUI/image/GenerateReport_CreateNewReport2x.png"));
        m_toolButtonCreateNewReport->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButtonCreateNewReport->setText(QStringLiteral("新建报告"));
        m_toolButtonCreateNewReport->setEnabled(true);
        toolBar->addWidget(m_toolButtonCreateNewReport);
        connect(m_toolButtonCreateNewReport, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_CreateNewReport);

        ElaToolButton* toolButtonTemplateDefined = new ElaToolButton(this);
        toolButtonTemplateDefined->setIcon(QIcon(":/QUI/image/GenerateReport_TemplateDefined2x.png"));
        toolButtonTemplateDefined->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButtonTemplateDefined->setText(QStringLiteral("模板定义"));
        toolBar->addWidget(toolButtonTemplateDefined);
        connect(toolButtonTemplateDefined, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_TemplateDefined);

        ElaToolButton* toolButtonTemplateImport = new ElaToolButton(this);
        toolButtonTemplateImport->setIcon(QIcon(":/QUI/image/GenerateReport_TemplateImport2x.png"));
        toolButtonTemplateImport->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButtonTemplateImport->setText(QStringLiteral("导入模板"));
        toolBar->addWidget(toolButtonTemplateImport);
        connect(toolButtonTemplateImport, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_TemplateImport);

        ElaToolButton* toolButtonTemplateExport = new ElaToolButton(this);
        toolButtonTemplateExport->setIcon(QIcon(":/QUI/image/GenerateReport_TemplateExport2x.png"));
        toolButtonTemplateExport->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButtonTemplateExport->setText(QStringLiteral("导出模板"));
        toolBar->addWidget(toolButtonTemplateExport);
        connect(toolButtonTemplateExport, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_TemplateExport);

        ElaToolButton* toolButtonGenerateResultReport = new ElaToolButton(this);
        toolButtonGenerateResultReport->setIcon(QIcon(":/QUI/image/GenerateReport_GenerateResultReport2x.png"));
        toolButtonGenerateResultReport->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButtonGenerateResultReport->setText(QStringLiteral("报告生成"));
        toolBar->addWidget(toolButtonGenerateResultReport);
        connect(toolButtonGenerateResultReport, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_GemerateFinalReport);

        m_toolButtonReportRecordForm = new ElaToolButton(this);
        m_toolButtonReportRecordForm->setIcon(QIcon(":/QUI/image/GenerateReport_ReportRecordForm2x.png"));
        m_toolButtonReportRecordForm->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButtonReportRecordForm->setText(QStringLiteral("报告记录"));
        toolBar->addWidget(m_toolButtonReportRecordForm);
        connect(m_toolButtonReportRecordForm, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_ReportRecordForm);
      
        //ElaToolButton* toolButtonScreenshotToReport = new ElaToolButton(this);
        //toolButtonScreenshotToReport->setElaIcon(ElaIconType::CameraViewfinder);
        //toolButtonScreenshotToReport->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        //toolButtonScreenshotToReport->setText("截图至报告");
        //toolBar->addWidget(toolButtonScreenshotToReport);
        //connect(toolButtonScreenshotToReport, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick_screenshotToReport);

        this->addToolBar(Qt::TopToolBarArea, toolBar);
    }

    void MainWindow::toolButtonCreateNewReportStateUpdate(bool state)
    {
        m_toolButtonCreateNewReport->setEnabled(state);
    }

    void MainWindow::toolButtonReportRecordFormStateUpdate(bool state)
    {
        m_toolButtonReportRecordForm->setEnabled(state);
    }

    void MainWindow::statusBarPromptInformation(QString informationText)
    {
        //状态栏
        ElaStatusBar* statusBar = new ElaStatusBar(this);
        //ElaText* statusText = new ElaText(informationText, this);
        //statusText->setTextPixelSize(14);
        //statusBar->addWidget(statusText);
        statusBar->showMessage(informationText, 3000);//显示提示信息，3s后自动消失
        this->setStatusBar(statusBar);
    }

    void MainWindow::initContentWidget()
    {
        m_centerWidget = new CenterWidget(this);
        addPageNode("CenterWidget", m_centerWidget, ElaIconType::LocationArrow);
    }

    void MainWindow::slots_Timer()
    {
        QTextStream input(stdin, QIODevice::ReadOnly);
        QString msg = input.readLine();

        auto list_str = msg.split("{--}");
        foreach(auto var, list_str)
        {
            if (!(var.isEmpty()))
            {
                auto list_info = var.split("{||}");
                if (list_info.count() == 2 && list_info[0] == "screenshootToReport")
                {
                    if (list_info[1] == "YES")
                    {
                        QTimer::singleShot(0, this, &MainWindow::action_screenshotToReport);
                    }
                }
            }
        }

    }

    void MainWindow::saveProjectData()
    {
        FinalReportDataInstance->writeConfig();
    }

    void MainWindow::slot_showMiniFloatingWindow()
    {
        m_miniFloatingWindow->setFixedSize(50, 50);
        m_miniFloatingWindow->setMainWindow(this);//yr-设置主窗口
        m_miniFloatingWindow->SetPixmap(QPixmap(":/QUI/image/GenerateReport_CreateNewReport2x.png"));
        //m_miniFloatingWindow->move(pos());//设置浮窗的初始位置
        m_miniFloatingWindow->show();
    }

}
